<template>
	<div class="form-item-time">
		<van-field :label="label" :required="required" :disabled="disabled">
			<template #input>
				<input :type="htmlInputType" :step="stepAttr" :disabled="disabled" v-model="innerValue" @change="emitChange" />
			</template>
		</van-field>
	</div>
</template>

<script>
import { ref, watch, computed } from 'vue'
import dayjs from 'dayjs'

export default {
	name: 'FormItemTime',
	props: {
		modelValue: { type: String, default: '' },
		itemKey: { type: String, default: '' },
		label: { type: String, default: '' },
		required: { type: Boolean, default: false },
		disabled: { type: Boolean, default: false },
		type: { type: String, default: 'datetime' },
		formatter: { type: String, default: 'YYYY-MM-DD HH:mm:ss' },
		minDate: { type: Number, default: () => dayjs().add(-2, 'year').valueOf() },
		maxDate: { type: Number, default: () => dayjs().add(2, 'year').valueOf() },
	},
	emits: ['update:modelValue', 'confirm', 'change'],
	setup(props, { emit }) {
		const innerValue = ref(props.modelValue)
		watch(
			() => props.modelValue,
			(nv) => {
				innerValue.value = nv
			}
		)
		// precision: day | hour | minute
		// 根据 formatter 推断精度，若包含分则 minute，若包含时则 hour，否则 day
		const precision = computed(() => {
			if (props.formatter.includes('mm')) return 'minute'
			if (props.formatter.includes('HH')) return 'hour'
			return 'day'
		})
		const htmlInputType = computed(() => (precision.value === 'day' ? 'date' : 'datetime-local'))
		// step 属性: 精确到分钟时步长60秒(默认), 可自定义为 '60'
		const stepAttr = computed(() => (precision.value === 'minute' ? 60 : undefined))
		const emitChange = () => {
			let formatted = innerValue.value
			if (formatted) {
				formatted = precision.value === 'day' ? dayjs(formatted).format('YYYY-MM-DD') : dayjs(formatted).format(props.formatter)
			}
			emit('update:modelValue', formatted)
			emit('confirm', { [props.itemKey]: formatted })
			emit('change', { [props.itemKey]: formatted })
		}
		return { innerValue, emitChange, htmlInputType, stepAttr }
	},
}
</script>

<style lang="less" scoped>
</style>